package com.flyduck.modules.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.entity.AppComment;
import com.flyduck.entity.AppOrder;
import com.flyduck.entity.AppOrderItem;
import com.flyduck.entity.AppProduct;
import com.flyduck.mapper.AppCommentMapper;
import com.flyduck.mapper.AppOrderItemMapper;
import com.flyduck.mapper.AppOrderMapper;
import com.flyduck.mapper.AppProductMapper;
import com.flyduck.modules.app.constant.AppConstant;
import com.flyduck.manager.AppOrderManager;
import com.flyduck.manager.AppUploadManager;
import com.flyduck.modules.app.vo.comment.AppCommentDetailsRespVO;
import com.flyduck.utils.BeanUtils;
import com.flyduck.utils.TokenUtils;
import com.flyduck.modules.app.service.AppCommentService;
import com.flyduck.modules.app.vo.comment.AppCommentProductRespVO;
import com.flyduck.modules.app.vo.comment.AppCommentRespVO;
import com.flyduck.modules.app.vo.comment.AppCommentPostReqVO;
import com.flyduck.utils.PageUtils;
import com.flyduck.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-23 21:38
 **/
@Service
public class AppCommentServiceImpl implements AppCommentService {

    @Resource
    private AppCommentMapper appCommentMapper;
    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private AppOrderItemMapper appOrderItemMapper;
    @Resource
    private AppOrderManager appOrderManager;
    @Resource
    private AppUploadManager appUploadManager;
    @Resource
    private AppProductMapper appProductMapper;

    @Override
    public Page<AppCommentRespVO> getCommentPageByProductId(Page page, Long productId) {
        return appCommentMapper.getCommentPageByProductId(page,productId);
    }

    /**
     *
     * @param page
     * @param status 0:未评论 1:已评论
     * @return
     */
    @Override
    public Page<AppCommentProductRespVO> getCommentProductPageByStatus(Page page, Integer status) {
        Long userId = tokenUtils.getCurrentUserId();
        //1、获取待评论的订单列表，就是已完成的订单列表
        List<Object> completedOrderIds = appOrderMapper.selectObjs(
                new LambdaQueryWrapper<AppOrder>()
                        .eq(AppOrder::getUserId, userId)
                        .eq(AppOrder::getOrderStatus, AppConstant.OrderStatus.COMPLETED.getCode())
                        .select(AppOrder::getId)
        );


        //2、再获取已完成的订单列表的待评论的商品
        Page<AppOrderItem> appOrderItemPage = new Page<>();
        if(CollectionUtil.isNotEmpty(completedOrderIds)){
            appOrderItemPage = appOrderItemMapper.selectPage(
                    page,
                    new LambdaQueryWrapper<AppOrderItem>()
                            .in(AppOrderItem::getOrderId, completedOrderIds)
                            .isNull(status == 0, AppOrderItem::getCommentId)
                            .isNotNull(status == 1, AppOrderItem::getCommentId)
                            .orderByDesc(AppOrderItem::getCreated)
            );
        }
        return PageUtils.convert(appOrderItemPage,AppCommentProductRespVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long postComment(MultipartFile[] pics, AppCommentPostReqVO appCommentPostReqVO) {
        Long userId = tokenUtils.getCurrentUserId();
        //1、条件判断
        AppOrderItem appOrderItem = appOrderItemMapper.selectById(appCommentPostReqVO.getOrderItemId());
        if(appOrderItem.getCommentId() != null){
            throw new BusinessException("请勿重复评论");
        }
        AppOrder appOrder = appOrderManager.verifyAppOrderById(appOrderItem.getOrderId());
        if (AppConstant.OrderStatus.COMPLETED.getCode() != appOrder.getOrderStatus()) {
            throw new BusinessException("该订单无法评论");
        }

        //2、图片处理
        List<String> picUrls = new ArrayList<>();
        if(ArrayUtil.isNotEmpty(pics)){
            try {
                picUrls = appUploadManager.upload(pics, 0.5f, 0.2);
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException("图片上传失败");
            }
        }

        //3、保存评论
        AppComment appComment = new AppComment();
        appComment.setUserId(userId);
        appComment.setProductId(appOrderItem.getProductId());
        appComment.setOrderItemId(appOrderItem.getId());
        appComment.setOrderId(appOrder.getId());
        appComment.setContent(appCommentPostReqVO.getContent());
        appComment.setScore(appCommentPostReqVO.getScore());
        appComment.setImages(StringUtils.join(";", picUrls));
        appComment.setCreated(LocalDateTime.now());
        appCommentMapper.insert(appComment);

        //4、更新订单明细的评论id和评论时间
        appOrderItem.setCommentId(appComment.getId());
        appOrderItem.setCommentTime(LocalDateTime.now());
        appOrderItemMapper.updateById(appOrderItem);

        //5、商品评论数量+1
        appProductMapper.update(
                new LambdaUpdateWrapper<AppProduct>()
                 .eq(AppProduct::getId,appOrderItem.getProductId())
                .setSql("comments = comments + 1")
        );

        return appComment.getId();

    }

    @Override
    public AppCommentDetailsRespVO getCommentDetailsById(Long id) {
        AppComment appComment = appCommentMapper.selectById(id);
        return BeanUtils.toBean(appComment,AppCommentDetailsRespVO.class);

    }
}
